package com.koron.css2.clientCenter.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.clientCenter.bean.UserChangeItemBean;
import com.koron.css2.clientCenter.bean.UserCloseBean;
import com.koron.css2.clientCenter.bean.UserCloseDetailBean;
import com.koron.css2.clientCenter.mapper.ChangeUserMapper;
import com.koron.css2.clientCenter.mapper.CloseUserMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.util.Constant;
import com.koron.util.JsonUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户销户编辑
 * @author 甄玉晴
 *
 */
public class CloseUserUpdate implements ServerInterface {

	@Override
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		try {
			CloseUserMapper mapper = factory.getMapper(CloseUserMapper.class);
			UserCloseBean bean = JsonUtils.objectToPojo(req.getData(), UserCloseBean.class);
			ChangeUserMapper cmapper = factory.getMapper(ChangeUserMapper.class);
			if (bean.getList().size()!=0){
				//如果调用修改接口，而且list不为空  ，说明重新导入了销户详情列表，则删除之前的变更临时记录
				cmapper.userChangeItemDelete(bean.getId(),2);
				//删除之前销户信息
				mapper.userCloseDetailDelete(bean.getId());
				//批量修改销户详情表和销户表关联
//				mapper.userCloseBatchUpdate(bean.getList(),bean.getId());
				//批量插入销户详情信息
				mapper.userCloseBatchAdd(bean.getList(),bean.getId());
				//重新导入新的销户信息列表后，重新添加变更记录表
				List<UserChangeItemBean> item = new ArrayList<UserChangeItemBean>();
				//记录每个用户的变更记录
				for (UserCloseDetailBean userCloseDetailBean: bean.getList()){
					UserChangeItemBean ubean = new UserChangeItemBean();
					ubean.setReceiptId(bean.getId());
					ubean.setReceiptType("USER_CLOSE");
					ubean.setBillNo(bean.getBillNo());
					ubean.setCreateInfo(userInfo);
					ubean.setChangeItem("用户状态");
					ubean.setOldItemValue("1");
					ubean.setNewItemValue("0");
					ubean.setUserNo(userCloseDetailBean.getUserNo());
					item.add(ubean);
				}
				cmapper.userChangeItemAdd(item, 2);
			}
//			UserCloseBean before = mapper.getUserCloseInfoById(bean.getId());
			// 获取停用信息
			bean.setUpdateInfo(userInfo);
			//记录销户信息
			mapper.userCloseUpdate(bean);
			return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", void.class);
		} catch (Exception e) {
			logger.error("销户编辑失败", e);
			return MessageBean.create(Constant.MESSAGE_INT_FAIL, "销户编辑失败", void.class);
		}
	}

}
